<?php
namespace app\api\controller\mytool;
use think\Db;
use think\facade\Env;
use think\Controller;
use app\api\controller\Base;
use app\api\controller\Pub;
use app\common\model\user\User;
use app\common\model\company\Company;
use app\common\model\company\Contract;
use app\api\controller\mytool\Mytool;
//require Env::get('vendor_path') . "autoload.php";
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use think\facade\Cache;


class Wechat extends Base
{
    public function index()
    {
        return 'hello,';
    }

    /**
     * 获取微信授权
     */
    public static function WeChatOAuth()
    {
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
            'oauth'         => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => SERVERURL . '/api/wechat/WeChatOAuth2',
            ],
        ];

        $app   = Factory::officialAccount($config);
        $oauth = $app->oauth;

        $oauth->redirect()->send();
        // $oauth->redirect();
    }
    /**
     * 微信授权后请求用户信息，并登录系统获取jwt
     */
    public function WeChatOAuth2()
    {
        try {
            $code = input('code');
            if (empty($code)) {
                return myerr('缺少参数，请重新登录');
            }
            $config = [
                'app_id'        => WXAPPID,
                'secret'        => WXSERCRET,
                'token'         => WXTOKEN,
                'response_type' => 'array',
            ];

            $app   = Factory::officialAccount($config);
            $oauth = $app->oauth;
            // 获取 OAuth 授权结果用户信息
            $user     = $oauth->user();
            $user     = (array) $user;
            $userdata = $user["\0*\0attributes"];
            //判断是否存在此微信id
            $data    = User::iswechatid($userdata['id']);
            $user_id = '';
            if ($data['code']) {
                //找到微信openid-》判断用户信息是否需要更新
                $user_id = $data['msg'];
            } else {
                //没有找到账号-》创建账号
                $adduserdata = User::adduser($userdata['id']);
                $user_id     = $adduserdata['msg'];
            }
            $sb = User::user_login_state($user_id);
            if ($sb['code']) {
                $sb = Pub::getjwtkeyarray($user_id);
                if (!$sb['code']) {
                    return myerr($sb['msg']);
                }
                $user    = User::get($user_id);
                $options = empty(!$user['Iphone']) ? '' : 'register';
                return myok(Pub::pub_login_after($user), '', $options);
            } else {
                return myerr($sb['msg']);
            }
        } catch (Exception $e) {
            return myerr('请重新登录');
        }
    }
    /**
     * 去除emoji
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    public function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str
        );
        return $str;
    }

    /**
     * 推送直播间订阅消息
     */
    public static function SendMessage($data, $fk = 0)
    {
        if ($fk > WECHATERRORNUMBER) {
            return serr(['msg' => '错误次数过多', 'data' => $data]);
        }
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
        ];
        if (empty($data['touser'][0])) {
            return serr(['msg' => '缺少用户openid。', 'data' => $data]);
        }
        $app     = Factory::officialAccount($config);
        $msgdata = $data['msgdata'];
        $ndata   = [
            'template_id' => $data['temp'],
            'data'        => $msgdata,
        ];
        if (!empty($msgdata['url'])) {
            $ndata['url'] = $msgdata['url'];
        }

        if (empty($data['success'])) {
            $data['success'] = [];
        }
        if (empty($data['error'])) {
            $data['error'] = [];
        }
        for ($i = 0; $i < count($data['touser']); $i++) {
            try {
                $ndata['touser'] = $data['touser'][$i];
                $re              = $app->template_message->send($ndata);
                if ($re['errcode'] == 0) {
                    $data['success'][] = $data['touser'][$i];
                }else{
                    // 推送失败的话记录显示原因
                    // dump($ndata);
                    // dump($re);
                }
            } catch (\Exception $e) {
                if(!empty($data['touser']) && !empty($data['touser'][$i]) ){
                   $data['error'][] = $data['touser'][$i]; 
                }
            }
        }
        if (!empty($data['error'])) {
            $data['touser'] = $data['error'];
            return self::SendMessage($data, $fk + 1);
        } else {
            return sok('推送已完成');
        }
    }
    public function setmenu()
    {
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
        ];

        $app = Factory::officialAccount($config);

        $buttons = [
            [
                "type" => "view",
                "name" => "进入平台",
                "url"  => ACCESS_ORIGIN.'/h5/' ,
            ],
        ];
        $app->menu->create($buttons);
        $a = $app->menu->create($buttons);
        dump($a);
    }

    /**
     * 微信jssdk签名验证，与前端核对。
     * @return [type] [返回配置文件]
     */
    public static function jssdk()
    {
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
        ];

        $app = Factory::officialAccount($config);
        $url = input('url');
        if (!empty($url)) {
            $app->jssdk->setUrl($url);
        }
        return $app->jssdk->buildConfig(['onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'scanQRCode',
            'onMenuShareWeibo', 'updateAppMessageShareData',
            'updateTimelineShareData', 'openLocation', 'getLocation', 'openLocation'], $debug = false, $beta = false, $json = true);
    }

    /**
     * 判断用户是否已关注本公众号
     * @return [int] [没关注返回0false，关注后返回true,没有绑定微信返回2]
     */
    public static function isfollow()
    {
        $userlogininfo = Pub::getuserid(input('token'));
        if ($userlogininfo['code']) {
            $UserId = $userlogininfo['msg'];
        } else {
            $UserId = Session::get('user_id');
        }
        $userdata = db('user')->where('user_id', $UserId)->find();
        if (empty($userdata['wechat_openid'])) {
            return false;
        }
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
        ];
        $app  = Factory::officialAccount($config);
        $user = $app->user->get($userdata['wechat_openid']);
        if ($user['subscribe'] == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 返回一个微信公众号二维码
     * @return [type] [返回配置文件]
     */
    public static function qrcode($str,$file='')
    {
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
        ];

        $app    = Factory::officialAccount($config);
        $result = $app->qrcode->temporary($str, 24 * 3600);
        // Array
        // (
        //     [ticket] => gQFD8TwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyTmFjVTRWU3ViUE8xR1N4ajFwMWsAAgS2uItZAwQA6QcA
        //     [expire_seconds] => 518400
        //     [url] => http://weixin.qq.com/q/02NacU4VSubPO1GSxj1p1k
        // )
        if(empty($file)){
            return $result['url'];
        }else if($file=='ticket'){
            return urlencode($result[$file]);
        }else{
             return $result[$file];
        }
    }
    
    /**
     * @return 处理微信公众号消息
     * 具体逻辑由MessageGuoLv来处理
     */
    public function msgserver()
    {
        $config = [
            'app_id'        => WXAPPID,
            'secret'        => WXSERCRET,
            'token'         => WXTOKEN,
            'response_type' => 'array',
        ];
        $app = Factory::officialAccount($config);
        $app->server->push(function ($message) {
            $sb = self::MessageGuoLv($message);
            if($sb['code']==false){
                return $sb['message'];
            }
        });
        $response = $app->server->serve();
        // 将响应输出
        $response->send();
        exit;
    }
    /**
     * @param 微信公众号消息处理逻辑
     */
    public function MessageGuoLv($message)
    {
        switch ($message['MsgType']) {
            case 'event':
                if ($message['Event'] == 'SCAN') {
                    if (strstr($message['EventKey'], 'bind_hawa_'.SITEPERFIX.'_')) {
                        $id    = substr($message['EventKey'], strlen('bind_hawa_'.SITEPERFIX.'_'));
                        $data  = Company::user_getinfo($id);
                        $items = [
                            new NewsItem([
                                'title'       => '账号绑定提醒',
                                'description' => '欢迎使用本系统，点击消息即可绑定产废单位【'.$data['Name'].'】',
                                'url'         => WEBURL . 'hawabuss/bind?id='.$id,
                                'image'       => SERVERURL.'/logo.png',
                            ]),
                        ];
                        $news = new News($items);
                        return ['code' => false, 'message' => $news];
                    }else if (strstr($message['EventKey'], 'validate_contract_'.SITEPERFIX.'_')) {
                        $id    = substr($message['EventKey'], strlen('validate_contract_'.SITEPERFIX.'_'));
                        $data  = Contract::get($id);
                        $cdata  = Company::get($data['CompanyId']);
                        if(empty($data)){
                            return ['code' => false, 'message' => '感谢您使用合同防伪系统，没有找到您查找的相关合同，具体情况请联系我们，联系电话：'.CELLPHONE];
                        }
                        $items = [
                            new NewsItem([
                                'title'       => '合同防伪系统',
                                'description' => '检测到：委托方【'.$cdata['Name'].'】有效期至'.$data['EndTime'].'的合同，编号为：'.$data['OrderNumber'].'，具体内容请点击查看。',
                                'url'         => WEBURL . 'print/contract_rote?p='.$data['PrintPassword'],
                                'image'       => SERVERURL.'/success.png',
                            ]),
                        ];
                        $news = new News($items);
                        return ['code' => false, 'message' => $news];
                    }else if (strstr($message['EventKey'], 'login_')) {
                        //扫码登陆pc系统
                        $token    = $message['EventKey'];
                        $data  = Cache::get($token);
                        if(empty($data)||empty($data['code'])){
                            return ['code' => false, 'message' => '登陆失败，请重新扫码。如有问题请联系我们' .CELLPHONE];
                        }
                        //查询用户openid对应的userid
                        $user = User::iswechatid($message['FromUserName']);
                        if(!$user['code']){
                            return ['code' => false, 'message' => $user['msg'].'。如有问题请联系我们' .CELLPHONE];
                        }
                        $data['code'] = 'ok';
                        $data['msg'] = $user['msg'];
                        Cache::set($token,$data,360);
                        return ['code' => false, 'message' => '登陆成功'];
                    }

                }else if ($message['Event'] == 'subscribe') {
                    if (strstr($message['EventKey'], 'qrscene_bind_hawa_'.SITEPERFIX.'_')) {
                        $id    = substr($message['EventKey'], strlen('qrscene_bind_hawa_'.SITEPERFIX.'_'));
                        $data  = Company::user_getinfo($id);
                        $items = [
                            new NewsItem([
                                'title'       => '账号绑定提醒',
                                'description' => '欢迎使用本系统，点击消息即可绑定产废单位【'.$data['Name'].'】',
                                'url'         => WEBURL . 'hawabuss/bind?id='.$id,
                                'image'       => SERVERURL.'/logo.png',
                            ]),
                        ];
                        $news = new News($items);
                        return ['code' => false, 'message' => $news];
                    }else if (strstr($message['EventKey'], 'qrscene_validate_contract_'.SITEPERFIX.'_')) {
                        $id    = substr($message['EventKey'], strlen('qrscene_validate_contract_'.SITEPERFIX.'_'));
                        $data  = Contract::get($id);
                        if(empty($data)){
                            return ['code' => false, 'message' => '感谢您使用合同防伪系统，没有找到您查找的相关合同，具体情况请联系我们，联系电话：'.CELLPHONE];
                        }
                        $items = [
                            new NewsItem([
                                'title'       => '合同防伪系统',
                                'description' => '检测到编号为：【'.$data['OrderNumber'].'】的合同，具体内容请点击查看。',
                                'url'         => WEBURL . 'print/contract_rote?p='.$data['PrintPassword'],
                                'image'       => SERVERURL.'/success.png',
                            ]),
                        ];
                        $news = new News($items);
                        return ['code' => false, 'message' => $news];
                    }else{
                        return ['code' => false, 'message' => '感谢您的关注，我们愿与您共享数字时代的力量。如有需要请联系我们：'.CELLPHONE];
                    }
                }
                return ['code' => false, 'message' => '收到事件消息:' . $message['Event'] . '。    '];
                break;
            case 'text':
                $whr = new Wechathelper();
                return ['code' => false, 'message' => $whr->myinit($message)];
                break;
            case 'image':
                return ['code' => true, 'message' => '收到图片消息'];
                break;
            case 'voice':
                $whr = new Wechathelper();
                return ['code' => false, 'message' =>$whr->myinit($message)];
                break;
            case 'video':
                return ['code' => true, 'message' => '收到视频消息'];
                break;
            case 'location':
                return ['code' => true, 'message' => '收到坐标消息'];
                break;
            case 'link':
                return ['code' => true, 'message' => '收到链接消息'];
                break;
            case 'file':
                return ['code' => true, 'message' => '收到文件消息'];
            // ... 其它消息
            default:
                return ['code' => true, 'message' => '收到其它消息'];
                break;
        }
    }

    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }
}
